package com.ruoyi.socket.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

/***
 *  @description
 *  @author zhao
 *  @date: 2020/5/26
 *  @version: v1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Item2Tree {
    private Integer id;
    private Integer pid;
    private String name;
    private List<Item2Tree> children = new ArrayList<>();

    public Item2Tree(Integer id, Integer pid, String name) {
        this.id = id;
        this.pid = pid;
        this.name = name;
    }

    public static List<Item2Tree> listToTree(List<Item2Tree> items) {
//        JSONArray r = new JSONArray();
        if (null == items || items.isEmpty()) {
            return items;
        }
        List<Item2Tree> r = new ArrayList<>(items.size());
        JSONObject hash = new JSONObject();
        //将数组转为Object的形式，key为数组中的id
        for (int i = 0; i < items.size(); i++) {
            Item2Tree item = items.get(i);
            hash.put(item.getId().toString(), item);
        }

        //遍历结果集
        for (int j = 0; j < items.size(); j++) {
            //单条记录
            Item2Tree aVal = items.get(j);
            //在hash中取出key为单条记录中pid的值
            Item2Tree hashVP = (Item2Tree) hash.get(aVal.getPid().toString());
            //如果记录的pid存在，则说明它有父节点，将她添加到孩子节点的集合中
            if (hashVP != null) {
                //检查是否有child属性
                List<Item2Tree> children = hashVP.getChildren();
                if (children != null) {
                    children.add(aVal);
                    hashVP.setChildren(children);
                } else {
                    List<Item2Tree> ch = new ArrayList<>();

                    ch.add(aVal);
                    hashVP.setChildren(ch);
                }
            } else {
                r.add(aVal);
            }
        }
        return r;
    }


    public static void main(String[] args) {
        ArrayList<Item2Tree> list = new ArrayList<>();
        list.add(new Item2Tree(1, 0, "name1"));
        list.add(new Item2Tree(6, 0, "name1"));
        list.add(new Item2Tree(2, 1, "name2"));
        list.add(new Item2Tree(3, 2, "name3"));
        list.add(new Item2Tree(4, 3, "name4"));
        list.add(new Item2Tree(5, 3, "name5"));
        List<Item2Tree> items = listToTree(list);
        System.out.println(JSON.toJSONString(items));
        System.out.println(items);
    }

}
